package com.gmail.ceac13.servicos;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;

public class ImageServer {
	private static String ENDERECO = "http://connectme.scienceontheweb.net/getImage.php?imgname=";
	public static Drawable buscarImagem(String img, Context context) {
		SharedPreferences settings = context.getSharedPreferences("ConnectMe",context.MODE_PRIVATE);
		String endServer = settings.getString("servidor", "http://connectme.scienceontheweb.net/");
		//String endServer = settings.getString("servidor", "http://10.0.2.2/connectme/");
		endServer = endServer + "getImage.php?imgname=";
		Drawable image = Drawable.createFromPath(img);
		
		if (image == null) {
			
			try {
				//URL url = new URL(ENDERECO + img);
				URL url = new URL(endServer + img);
				FileOutputStream out = context.openFileOutput(img, context.MODE_PRIVATE);
				URLConnection ucon = url.openConnection();
				InputStream is = ucon.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayBuffer baf = new ByteArrayBuffer(50);
                int current = 0;
                while ((current = bis.read()) != -1) {
                        baf.append((byte) current);
                }

                out.write(baf.toByteArray());
                out.close();
                image = Drawable.createFromStream(context.openFileInput(img), img);
                
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return image;
	}
}
